package org.kl.bf.web.basic;

import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.ServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.kl.bf.entity.basic.DataRole;
import org.kl.bf.entity.basic.Role;
import org.kl.bf.entity.basic.User;
import org.kl.bf.entity.easyui.EasyuiUtils;
import org.kl.bf.entity.easyui.Json;
import org.kl.bf.service.basic.DataRoleService;
import org.kl.bf.service.basic.RoleService;
import org.kl.bf.service.basic.UserService;
import org.kl.bf.utils.KLServlets;
import org.kl.bf.web.base.BasicController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springside.modules.web.MediaTypes;

/**
 * 给系列用户分配角色
 * 
 * @Author ymc
 * @CreateTime 2014-3-13 下午9:34:36
 */
@Controller
@RequestMapping(value = "/basic/roleUsers")
public class RoleUsersController extends BasicController {

	@Autowired
	private UserService userService;
	@Autowired
	private DataRoleService dataRoleService;
	@Autowired
	private RoleService roleService;

	@RequiresPermissions("roleUsers:list")
	@RequestMapping(method = RequestMethod.GET)
	public String list() {
		return "basic/roleUsersList";
	}

	@RequiresPermissions("roleUsers:list")
	@RequestMapping(value = "userDataGrid", produces = MediaTypes.JAVASCRIPT_UTF_8)
	@ResponseBody
	public String userDataGrid(@RequestParam(value = "pageNumber", defaultValue = "1") int pageNumber,
			@RequestParam(value = "rows", defaultValue = PAGE_SIZE) int pageSize,
			@RequestParam(value = "sort", defaultValue = "trueName") String sortType,
			@RequestParam(value = "order", defaultValue = "asc") String orderType, Model model, ServletRequest request) {
		Map<String, Object> searchParams = KLServlets.getParametersStartingWith(request, SEARCH_PREFIX);
		Page<User> users = userService.getUser(searchParams, pageNumber, pageSize, sortType, orderType);
		return EasyuiUtils.buildEasyuiGridJsonString(users.getContent(), (int) users.getTotalElements());
	}

	@RequiresPermissions("roleUsers:update")
	@RequestMapping(value = "addRoles", method = RequestMethod.POST, produces = MediaTypes.JAVASCRIPT_UTF_8)
	@ResponseBody
	public String addRoles(ServletRequest request) {
		String userIds = request.getParameter("userIds");
		String roleId = request.getParameter("roleId");
		String dataRoleId = request.getParameter("dataRoleId");
		Json json = new Json();
		if (StringUtils.isBlank(userIds)) {
			json.setMsg("配置失败，无法获取用户标识，请先勾选用户");
			json.setSuccess(false);
		} else {
			if (StringUtils.isBlank(dataRoleId) && StringUtils.isBlank(roleId)) {
				json.setMsg("配置失败，为选择角色或数据角色！");
				json.setSuccess(false);
			} else {
				userService.addRoleUsers(userIds, dataRoleId, roleId);
				json.setMsg("配置成功");
				json.setSuccess(true);
			}
		}
		return jsonMapper.toJson(json);
	}

	/**
	 * 页面勾选用户时给角色配置用户
	 * 
	 * @param userIds
	 * @param roleId
	 * @param request
	 * @return
	 */
	@RequiresPermissions("roleUsers:update")
	@RequestMapping(value = "check", method = RequestMethod.POST, produces = MediaTypes.JSON_UTF_8)
	@ResponseBody
	public String check(@RequestParam(value = "userIds", defaultValue = "") String userIds,
			@RequestParam(value = "roleId", defaultValue = "") String roleId, ServletRequest request) {
		Json json = new Json();
		if (StringUtils.isBlank(userIds)) {
			json.setMsg("配置失败，无法获取用户标识，请先勾选用户");
			json.setSuccess(false);
		} else {
			try {
				userService.addRoleUsersWithSQL(userIds, roleId);
				json.setMsg("配置成功");
				json.setSuccess(true);
			} catch (Exception e) {
				e.printStackTrace();
				json.setMsg("配置失败：" + e.getMessage());
				json.setSuccess(false);
			}
		}
		return jsonMapper.toJson(json);
	}

	/**
	 * 页面勾选用户时给角色配置用户
	 * 
	 * @param userIds
	 * @param roleId
	 * @param request
	 * @return
	 */
	@RequiresPermissions("roleUsers:update")
	@RequestMapping(value = "uncheck", method = RequestMethod.POST, produces = MediaTypes.JSON_UTF_8)
	@ResponseBody
	public String uncheck(@RequestParam(value = "userIds", defaultValue = "") String userIds,
			@RequestParam(value = "roleId", defaultValue = "") String roleId, ServletRequest request) {
		Json json = new Json();
		if (StringUtils.isBlank(userIds)) {
			json.setMsg("取消配置失败，无法获取用户标识，请先勾选用户");
			json.setSuccess(false);
		} else {
			try {
				userService.deleteRoleUsersWithSQL(userIds, roleId);
				json.setMsg("取消配置成功");
				json.setSuccess(true);
			} catch (Exception e) {
				e.printStackTrace();
				json.setMsg("取消配置失败：" + e.getMessage());
				json.setSuccess(false);
			}
		}
		return jsonMapper.toJson(json);
	}

	@RequiresPermissions("roleUsers:list")
	@RequestMapping(value = "dataRolesDataGrid", method = RequestMethod.GET, produces = MediaTypes.JAVASCRIPT_UTF_8)
	@ResponseBody
	public String dataRolesDataGrid(@RequestParam(value = "sort", defaultValue = "id") String sortType,
			@RequestParam(value = "order", defaultValue = "desc") String orderType, Model model, ServletRequest request) {
		Map<String, Object> searchParams = KLServlets.getParametersStartingWith(request, SEARCH_PREFIX);
		List<DataRole> drList = dataRoleService.getAllDataRole(searchParams, sortType, orderType);
		return EasyuiUtils.buildEasyuiGridJsonString(drList, drList.size());
	}

	@RequiresPermissions("roleUsers:list")
	@RequestMapping(value = "rolesDataGrid", method = RequestMethod.GET, produces = MediaTypes.JAVASCRIPT_UTF_8)
	@ResponseBody
	public String rolesDataGrid(@RequestParam(value = "sort", defaultValue = "id") String sortType,
			@RequestParam(value = "order", defaultValue = "desc") String orderType, Model model, ServletRequest request) {
		Map<String, Object> searchParams = KLServlets.getParametersStartingWith(request, SEARCH_PREFIX);
		List<Role> rList = roleService.getAllRole(searchParams, sortType, orderType);
		return EasyuiUtils.buildEasyuiGridJsonString(rList, rList.size());
	}

	@RequiresPermissions("roleUsers:list")
	@RequestMapping(value = "jsonRoleUsers", method = RequestMethod.GET, produces = MediaTypes.JAVASCRIPT_UTF_8)
	@ResponseBody
	public String jsonRoleUsers(ServletRequest request) {
		String roleId = request.getParameter("roleId");
		Json json = new Json();
		if (StringUtils.isNotBlank(roleId)) {
			Role role = roleService.getRole(roleId);
			Set<User> userSet = new HashSet<User>();
			List<User> userList = userService.getAllUser();
			for (int i = 0; i < userList.size(); i++) {
				User u1 = userList.get(i);
				if (u1.getRoleSet().contains(role)) {
					userSet.add(u1);
				}
			}
			json.setMsg("获取成功,用户" + (role != null && userSet != null ? userSet.size() : 0) + "个");
			json.setSuccess(true);
			json.setObj(userSet);
		} else {
			json.setSuccess(false);
			json.setMsg("获取角色标识失败，无法下一步操作");
		}
		return jsonMapper.toJson(json);
	}

	@RequiresPermissions("roleUsers:list")
	@RequestMapping(value = "jsonDataRoleUsers", method = RequestMethod.GET, produces = MediaTypes.JAVASCRIPT_UTF_8)
	@ResponseBody
	public String jsonDataRoleUsers(ServletRequest request) {
		String dataRoleId = request.getParameter("dataRoleId");
		Json json = new Json();
		if (StringUtils.isNotBlank(dataRoleId)) {
			DataRole dataRole = dataRoleService.getDataRole(dataRoleId);
			List<User> userList = userService.getAllUser();
			Set<User> dataRoleUserSet = new HashSet<User>();
			for (int i = 0; i < userList.size(); i++) {
				User u1 = userList.get(i);
				if (u1.getDataRoleSet().contains(dataRole)) {
					dataRoleUserSet.add(u1);
				}
			}
			json.setMsg("获取成功，用户" + (dataRole != null && dataRoleUserSet != null ? dataRoleUserSet.size() : 0) + "个");
			json.setSuccess(true);
			json.setObj(dataRoleUserSet);
		} else {
			json.setSuccess(false);
			json.setMsg("获取数据角色标识失败，无法下一步操作");
		}
		return jsonMapper.toJson(json);
	}

	/**
	 * 所有RequestMapping方法调用前的Model准备方法, 实现Struts2
	 * Preparable二次部分绑定的效果,先根据form的id从数据库查出Task对象,再把Form提交的内容绑定到该对象上。
	 * 因为仅update()方法的form中有id属性，因此仅在update时实际执行.
	 */
	@ModelAttribute
	public void getUser(@RequestParam(value = "id", defaultValue = "-1") String id, Model model) {
		if (!id.equals("-1")) {
			model.addAttribute("user", userService.getUser(id));
		}
	}
}
